package engine.mail;

import java.util.Collection;

import javax.mail.Address;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.MimeMessageHelper;

import engine.content.IContent;

public class MimeMessageWrapper implements IMailMessage<MimeMessage> {
	MimeMessage mm;
	MimeMessageHelper helper;
	
	public MimeMessageWrapper(MimeMessage mm) {
		this.setMessage(mm);
	}
	

	@Override
	public void setSender(String sender) throws Exception {
		mm.setSender(new InternetAddress(sender));

	}


	public MimeMessageHelper getHelper() {
		return helper;
	}


	@Override
	public void setReplyTo(String replyTo)  throws Exception{
		mm.setReplyTo(new Address[] {new InternetAddress(replyTo)});
	}


	@Override
	public void setTo(Collection<String> to) throws Exception {
		Address[] a = new Address[to.size()];
		int i=0;
		for (String s : to){
			a[i] = new InternetAddress(s);
			i++;
		}
		mm.addRecipients( RecipientType.BCC, a );	
	}


	@Override
	public void setSubject(String subject) throws Exception{
		mm.setSubject(subject);
	}


	@Override
	public void setHtmlBody(String htmlBody) throws Exception{
		if (helper != null) {
			helper.setText(htmlBody, true);
		} else {
			mm.setContent(htmlBody, "text/html");			
			mm.addHeader("Content-Type", "text/html");
		}
	}

	@Override
	public void addHeader(String header, String value) throws Exception{
		this.mm.addHeader(header, value);
	}

	@Override
	public MimeMessage getMessage() {
		return mm;
	}

	@Override
	public void setMessage(MimeMessage message) {
		this.mm = message;	
	}

	public void setMimeMessageHelper(MimeMessageHelper helper) {
		if (this.helper == null) {
			this.helper = helper;			
		}
	}


	@Override
	public void addAttachment(IContent content, Resource res,
			IMailMessage message, String fileName, String fileId)
			throws Exception {
		if (helper != null) {
			helper.addInline(fileId, res, fileId + "." + content.getContentType());
		}
		
	}
}
